import router from '../router'
import store from '../store'
import getDeviceInfo from './deviceInfo'
import axios from 'axios'
import consts from './consts'

const selfConfigPages = ['companyDetails', 'brandNameCardDetail', 'successfulCaseDetail'] // 页面内会自己配置分享信息
const needReloadPages = ['brandNameCardDetail', 'purposeOfActivity', 'successfulCaseDetail', 'brandNameCard', 'successfulCase', 'homePage', 'index'] // 需要重新加载页面才能分享 ios
let withCompanyInfo = false
let configUrl = ''
let configData
let companyName
let img
export const init = () => {
  if (getDeviceInfo().isIOS && getDeviceInfo().isWeiXin) {
    // 如果是ios 进来时候刷新一次页面 后面就跟安卓一样了
    // if (!window.sessionStorage.getItem('wxConfigReload')) {
    //   window.sessionStorage.setItem('wxConfigReload', true)
    //   setTimeout(() => {
    //     window.location.reload()
    //   }, 100)
    // }
    configUrl = window.location.href
  }
}

router.beforeEach((to, from, next) => {
  if (getDeviceInfo().isIOS && to.path !== window.location.pathname && needReloadPages.indexOf(to.name) !== -1) {
    // 点击企业详情刷新bug
    // 此处不可使用location.replace
    window.location.assign(to.fullPath)
  } else {
    next()
  }
})

router.afterEach((to, from) => {
  setTimeout(() => {
    // 现在不管是安卓还是ios 每次进入页面都去重新获取签名
    // if (getDeviceInfo().isAndroid) {
    configUrl = window.location.href
    // }
    if (selfConfigPages.indexOf(to.name) === -1) {
      getSignature()
    }
    if (selfConfigPages.indexOf(from.name) !== -1) {
      getSignature(store.state.voted) //离开品牌名片或成功案例详情页  离开企业详情页 重新配置微信分享 按照有没有投过票来配置
    }
  }, 10)
})

export const getSignature = (withCompanyInfoP, companyNameP, imgP) => {
  withCompanyInfo = withCompanyInfoP
  if (companyNameP) {
    companyName = companyNameP
  } else {
    companyName = store.state.shareData.companyName
  }
  if (imgP) {
    img = imgP
  } else {
    img = store.state.shareData.img
  }
  if (getDeviceInfo().isWeiXin) {
    axios
      .get(consts.baseUrl + 'wx_get_signature.php?url=' + encodeURIComponent(configUrl))
      .then(data => {
        configData = data.data.res
        shareConfig()
      })
      .catch(err => {
        console.log(err)
      })
  }
}

function shareConfig() {
  if (getDeviceInfo().isWeiXin && configData) {
    wx.config({
      debug: false,
      appId: configData.appid,
      timestamp: configData.timestamp,
      nonceStr: configData.nonceStr,
      signature: configData.signature,
      jsApiList: [
        // 需要调用的JS接口列表
        'checkJsApi', //判断当前客户端版本是否支持指定JS接口
        'onMenuShareTimeline', //分享给好友
        'onMenuShareAppMessage' //分享到朋友圈
      ]
    })
    wx.ready(() => {
      configShare()
    })
    wx.error(function () {
      // 如果是在ios端 微信配置失败后 进行一次页面重新加载
      // console.log(!window.sessionStorage.getItem('wxConfigReload'))
      // console.log(getDeviceInfo().isIOS)
      // if (!window.sessionStorage.getItem('wxConfigReload2') && getDeviceInfo().isIOS) {
      //   window.sessionStorage.setItem('wxConfigReload2', true)
      //   // window.location.reload()
      // }
    })
  }
}

function configShare() {
  let route = router.history.current
  let catid = route.query.catid || route.params.catid
  let itemid = route.params.itemid
  let shareTitle
  let shareUrl
  let shareDesc
  let shareImg
  if (catid) {
    if (route.name === 'successfulCaseDetail' && !route.query.catid) {
      // 成功案例详情页并且没有catid 说明是父级页面是没有catid的
      shareUrl = window.location.href
    } else {
      shareUrl = window.location.protocol + '//' + window.location.host + '/?catid=' + catid
    }
  } else {
    shareUrl = window.location.href
  }
  if (!catid && !itemid) {
    shareTitle = '品牌中网：数据铸就品牌，中网驱动消费'
    shareDesc = '品牌时代以“诚”见实力，数据时代以“精”赢未来，品牌中网以消费者及经营者为主，推出各个行业中的口碑品牌。'
    shareImg = 'http://img.brandzw.com/skin/default/images/shareLogo.png'
  } else if (withCompanyInfo) {
    if (itemid) {
      // 详情页，没有行业名称
      shareTitle = votedRandomTitle(companyName, '')
      shareDesc = votedRandomDesc(companyName, '')
    } else {
      shareTitle = votedRandomTitle(companyName, store.state.catName)
      shareDesc = votedRandomDesc(companyName, store.state.catName)
    }
    let urlArr = img.split('/')
    urlArr.splice(0, 3)
    let urlString = urlArr.join('/')
    let logoImgUrl = encodeURIComponent(urlString)
    shareImg = 'http://' + consts.domain + '/api/getimg.php?url=' + logoImgUrl
  } else {
    shareTitle = randomTitle(store.state.catName)
    shareDesc = randomDesc(store.state.catName)
    shareImg = 'http://img.brandzw.com/skin/default/images/shareLogo.png'
  }
  let shareConfigData = {
    title: shareTitle,
    link: shareUrl,
    desc: shareDesc,
    imgUrl: shareImg,
    success: function () {
      configShare()
    }
  }
  wx.onMenuShareTimeline(shareConfigData)
  wx.onMenuShareAppMessage(shareConfigData)
}

// 带品牌的随机分享标题 投过票 或者是在企业详情页
const votedRandomTitle = (title, catname) => {
  let randomNum = Math.ceil(Math.random() * 4)
  let randomTitle = ''
  switch (randomNum) {
    case 1:
      randomTitle = '品牌中网-' + title + '顶级品牌为梦而来！'
      break
    case 2:
      randomTitle = '2019年中国' + catname + '十大品牌参选者：' + title
      break
    case 3:
      randomTitle = title + '-入围品牌中网2019年中国' + catname + '十大品牌排行'
      break
    case 4:
      randomTitle = '品牌中网-' + title + '-2019年中国' + catname + '十大品牌排行'
      break
  }
  return randomTitle
}

// 带品牌的随机分享描述 投过票 或者是在企业详情页
const votedRandomDesc = (title, catname) => {
  let randomNum = Math.ceil(Math.random() * 4)
  let randomDesc = ''
  switch (randomNum) {
    case 1:
      randomDesc = title + '邀您一同助力2019中国' + catname + '十大品牌评选活动，见证品牌荣耀时刻！'
      break
    case 2:
      randomDesc = '铸经典品牌！成非凡梦想！2019' + catname + '圆梦启航！'
      break
    case 3:
      randomDesc = title + '入围2019年中国' + catname + '十大品牌排行，快来支持我吧！'
      break
    case 4:
      randomDesc = '助力品牌发展，打造优质品牌！' + title + '邀您为2019年中国' + catname + '十大品牌评选活动助力！'
      break
  }
  return randomDesc
}

// 默认的随机分享标题
const randomTitle = catname => {
  let defaultTitle = ''
  let randomNum = Math.ceil(Math.random() * 4)
  switch (randomNum) {
    case 1:
      defaultTitle = '品牌中网-2019年中国' + catname + '十大品牌排行'
      break
    case 2:
      defaultTitle = '品牌中网-2019年中国' + catname + '十大品牌评选活动强势来袭！'
      break
    case 3:
      defaultTitle = '品牌中网-2019年中国' + catname + '十大品牌评选活动'
      break
    case 4:
      defaultTitle = '2019年中国' + catname + '十大品牌举荐进行中-品牌中网'
      break
  }
  return defaultTitle
}
// 默认的随机分享描述
const randomDesc = catname => {
  let defaultDesc = ''
  let randomNum = Math.ceil(Math.random() * 4)
  switch (randomNum) {
    case 1:
      defaultDesc = '助力中国品牌，缔造品牌中国！2019年中国' + catname + '十大品牌评选活动等你助力！'
      break
    case 2:
      defaultDesc = '顶尖品牌决定非凡价值，实力缔造行业辉煌！十大品牌强势来袭！诚邀您的加入！'
      break
    case 3:
      defaultDesc = '逐鹿行业荣耀 见证品牌辉煌！十大品牌评选活动已开启，共同为十大品牌评选助力吧！'
      break
    case 4:
      defaultDesc = '展世界之品牌，示行业之风采！2019年中国' + catname + '十大品牌，期待您的参与！'
      break
  }
  return defaultDesc
}

export default {
  init,
  getSignature
}